package com.mdd.front.service.impl.yangyangLeadingEnterprise;

import com.aliyun.dypnsapi20170525.models.GetMobileResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.entity.user.User;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppEnterprise;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppUserData;
import com.mdd.common.entity.yangyangLeadingEnterprise.common.ErrorCode;
import com.mdd.common.entity.yangyangLeadingEnterprise.common.JsonReturn;
import com.mdd.common.entity.yangyangLeadingEnterprise.dto.AppEnterpriseDTO;
import com.mdd.common.entity.yangyangLeadingEnterprise.dto.AppUserDTO;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppEnterpriseMapper;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppUserDataMapper;
import com.mdd.common.util.RedisUtils;
import com.mdd.common.util.SessionHelper;
import com.mdd.common.util.SmsUtil;
import com.mdd.common.util.ToolUtils;
import com.mdd.common.util.aliyunOperatorLogin.GetMobile;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.cache.TokenLoginCache;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppUserService;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppUser;
import com.mdd.common.entity.yangyangLeadingEnterprise.param.LoginParam;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppUserMapper;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppUserCreateValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppUserSearchValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppUserUpdateValidate;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppUserDetailVo;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppUserListedVo;
import org.apache.commons.math3.util.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 【请填写功能名称】实现类
 * @author LikeAdmin
 */
@Service
public class TAppUserServiceImpl implements ITAppUserService {

    private static final String KEY = "login:front:token:";
    @Resource
    TAppUserMapper tAppUserMapper;

    @Resource
    TAppEnterpriseMapper appEnterpriseMapper;

    @Resource
    TAppUserDataMapper appUserDataMapper;
    @Autowired
    private TAppEnterpriseServiceImpl tAppEnterpriseServiceImpl;

    /**
     * 【请填写功能名称】列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<TAppUserListedVo>
     */
    @Override
    public PageResult<TAppUserListedVo> list(PageValidate pageValidate, TAppUserSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        QueryWrapper<TAppUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        tAppUserMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "like:nickname:str",
            "like:username:str",
            "=:password:str",
            "=:phone:str",
            "=:personalIntroduction@personal_introduction:str",
            "=:personalPic@personal_pic:str",
            "=:visitorNum@visitor_num:int",
        });

        IPage<TAppUser> iPage = tAppUserMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<TAppUserListedVo> list = new LinkedList<>();
        for(TAppUser item : iPage.getRecords()) {
            TAppUserListedVo vo = new TAppUserListedVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 根据id查询用户信息
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return TAppUser
     */
    @Override
    public TAppUserDetailVo detail(Integer id) {
        TAppUser model = tAppUserMapper.selectOne(
                new QueryWrapper<TAppUser>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        TAppUserDetailVo vo = new TAppUserDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 【请填写功能名称】新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(TAppUserCreateValidate createValidate) {
        TAppUser model = new TAppUser();
        model.setNickname(createValidate.getNickname());
        model.setUsername(createValidate.getUsername());
        model.setPassword(createValidate.getPassword());
        model.setPhone(createValidate.getPhone());
        model.setPersonalIntroduction(createValidate.getPersonalIntroduction());
        model.setPersonalPic(createValidate.getPersonalPic());
        model.setVisitorNum(createValidate.getVisitorNum());
        tAppUserMapper.insert(model);
    }

    /**
     * 修改用户信息
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(TAppUserUpdateValidate updateValidate) {
        TAppUser model = tAppUserMapper.selectOne(
                new QueryWrapper<TAppUser>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setNickname(updateValidate.getNickname());
        model.setUsername(updateValidate.getUsername());
        model.setPassword(updateValidate.getPassword());
        model.setPhone(updateValidate.getPhone());
        model.setPersonalIntroduction(updateValidate.getPersonalIntroduction());
        model.setPersonalPic(updateValidate.getPersonalPic());
        model.setVisitorNum(updateValidate.getVisitorNum());
        tAppUserMapper.updateById(model);
    }

    /**
     * 【请填写功能名称】删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        TAppUser model = tAppUserMapper.selectOne(
                new QueryWrapper<TAppUser>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        tAppUserMapper.delete(new QueryWrapper<TAppUser>().eq("id", id));
    }

    /**
     * 用户登录
     * @param param
     * @return
     */
    @Override
    public String appUserLogin(LoginParam param) {
        Integer loginType = param.getLoginType();
        String password = param.getPassword();
        String phone = param.getPhone();
        String phoneKey = param.getPhoneKey();
        String code = param.getCode();
        String codeKey = param.getCodeKey();
        String openId = param.getOpenId();
        String appleId = param.getAppleId();
        String appVersion = param.getAppVersion();
        String sysVersion = param.getSysVersion();
        Integer terminal = param.getTerminal();
        if(loginType==null ){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        //手机号密码登录
        if(loginType==1){
            if(phone==null || phone.isEmpty() || password==null || password.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            if(!ToolUtils.isValidPhoneNumber(phone)){
                return JsonReturn.fail("手机号格式不正确",301).toJsonStr();
            }
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).eq("is_delete", 1).last("limit 1"));
            if(user!=null && user.getId()!=null){
                String pwd = user.getPassword();
                if(pwd==null || pwd.isEmpty()){
                    return JsonReturn.fail("账号未设置密码",208).toJsonStr();
                }
                String pwdParam  = ToolUtils.makePassword(password);
                if(pwd.equals(pwdParam)){
                    user = createAppUserLoginToken(user);
                    String userPhone = user.getPhone();

                    user.setUpdateTime(new Date());
                    user.setAppVersion(appVersion);
                    user.setSysVersion(sysVersion);
                    user.setTerminal(terminal);
                    tAppUserMapper.updateById(user);
                    return JsonReturn.success().put("user",user)
                            .put("phoneFlag",userPhone!=null && !userPhone.isEmpty()?Boolean.TRUE:Boolean.FALSE)
                            .put("passwordFlag",Boolean.TRUE)
                            .put("registrationAgreementFlag",user.getRegistrationAgreementFlag()!=null && user.getRegistrationAgreementFlag()==1?Boolean.TRUE:Boolean.FALSE)
                            .toJsonStr();
                }
                return JsonReturn.fail("密码输入错误",202).toJsonStr();
            }else {
                return JsonReturn.fail("账号不存在",203).toJsonStr();
            }
        }
        //手机号验证码登录
        else if(loginType==2){
            if(phone==null || phone.isEmpty() || code==null || code.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            if(!ToolUtils.isValidPhoneNumber(phone)){
                return JsonReturn.fail("手机号格式不正确",301).toJsonStr();
            }
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).eq("is_delete", 1).last("limit 1"));
            if(user!=null && user.getId()!=null){
                if(!RedisUtils.exists(phone)){
                    return JsonReturn.fail("验证码已过期",210).toJsonStr();
                }
                Object codedata = RedisUtils.get(phone);
//                codedata=codeFinal;
                if(code.equals(codedata)){
                    user=createAppUserLoginToken(user);
                    RedisUtils.del(phone);

                    user.setUpdateTime(new Date());
                    user.setAppVersion(appVersion);
                    user.setSysVersion(sysVersion);
                    user.setTerminal(terminal);
                    tAppUserMapper.updateById(user);
                    return JsonReturn.success().put("user",user)
                            .put("phoneFlag",user.getPhone()!=null && !user.getPhone().isEmpty()?Boolean.TRUE:Boolean.FALSE)
                            .put("passwordFlag",user.getPassword()!=null && !user.getPassword().isEmpty()?Boolean.TRUE:Boolean.FALSE)
                            .put("registrationAgreementFlag",user.getRegistrationAgreementFlag()!=null && user.getRegistrationAgreementFlag()==1?Boolean.TRUE:Boolean.FALSE)
                            .toJsonStr();
                }
                return JsonReturn.fail("验证码输入错误",206).toJsonStr();
            }else {
                return JsonReturn.fail("手机号不存在",204).toJsonStr();
            }
        }
        //本机号码一键注册登录
        else  if(loginType==3){
            if(phoneKey==null || phoneKey.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            //阿里云一键登录
            try {
                Pair<Boolean, GetMobileResponseBody.GetMobileResponseBodyGetMobileResultDTO> pair = GetMobile.getMobile(phoneKey);
                if(pair.getKey()){
                    phone=pair.getValue().getMobile();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if(phone==null || phone.isEmpty()){
                return JsonReturn.fail("手机号一键登录失败",205).toJsonStr();
            }
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).eq("is_delete", 1).last("limit 1"));
            if(user!=null && user.getId()!=null){
                //登录
//                if(user.getPhoneKey()!=null && !user.getPhoneKey().isEmpty() && !user.getPhoneKey().equals(phoneKey)){
//                    return JsonReturn.fail("手机号一键登录验证失败",205).toJsonStr();
//                }
                user.setPhoneKey(phoneKey);
                user.setUpdateTime(new Date());
                user.setAppVersion(appVersion);
                user.setSysVersion(sysVersion);
                user.setTerminal(terminal);
                tAppUserMapper.updateById(user);
            }else{
                //注册
                TAppUser appUser = new TAppUser();
                appUser.setPhone(phone);
                System.out.println(phoneKey.length());
                appUser.setPhoneKey(phoneKey);
                appUser.setCreateTime(new Date());
                appUser.setUpdateTime(new Date());
                appUser.setIsDelete(1);
                user.setAppVersion(appVersion);
                user.setSysVersion(sysVersion);
                user.setTerminal(terminal);
                tAppUserMapper.insert(appUser);

                //初始化userdata数据
                initAppUserData(appUser.getId());
                user=appUser;
            }
            user=createAppUserLoginToken(user);
            return JsonReturn.success().put("user",user)
                    .put("phoneFlag",Boolean.TRUE)
                    .put("passwordFlag",user.getPassword()!=null && !user.getPassword().isEmpty()?Boolean.TRUE:Boolean.FALSE)
                    .put("registrationAgreementFlag",user.getRegistrationAgreementFlag()!=null && user.getRegistrationAgreementFlag()==1?Boolean.TRUE:Boolean.FALSE)
                    .toJsonStr();
        }
        //微信一键注册登录
        else  if(loginType==4){
            if(openId==null || openId.isEmpty() || phone==null || phone.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("open_id", openId).eq("is_delete", 1).last("limit 1"));
            if(user!=null && user.getId()!=null){
                //登录
                user.setUpdateTime(new Date());
                user.setAppVersion(appVersion);
                user.setSysVersion(sysVersion);
                user.setTerminal(terminal);
                tAppUserMapper.updateById(user);
            }else{
                //注册
                TAppUser appUser = new TAppUser();
                appUser.setOpenId(openId);
                appUser.setCreateTime(new Date());
                appUser.setUpdateTime(new Date());
                appUser.setPhone(phone);
                appUser.setIsDelete(1);
                user.setUpdateTime(new Date());
                user.setAppVersion(appVersion);
                user.setSysVersion(sysVersion);
                user.setTerminal(terminal);
                tAppUserMapper.insert(appUser);

                //初始化userdata数据
                initAppUserData(appUser.getId());
                user=appUser;
            }
            user=createAppUserLoginToken(user);
            return JsonReturn.success().put("user",user)
                    .put("phoneFlag",user.getPhone()!=null && !user.getPhone().isEmpty()?Boolean.TRUE:Boolean.FALSE)
                    .put("passwordFlag",user.getPassword()!=null && !user.getPassword().isEmpty()?Boolean.TRUE:Boolean.FALSE)
                    .put("registrationAgreementFlag",user.getRegistrationAgreementFlag()!=null && user.getRegistrationAgreementFlag()==1?Boolean.TRUE:Boolean.FALSE)
                    .toJsonStr();
        }
        //ios一键注册登录
        else  if(loginType==5){
            if(appleId==null || appleId.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("apple_id", appleId).eq("is_delete", 1).last("limit 1"));
            if(user!=null && user.getId()!=null){
                //登录
                user.setUpdateTime(new Date());
                user.setAppVersion(appVersion);
                user.setSysVersion(sysVersion);
                user.setTerminal(terminal);
                tAppUserMapper.updateById(user);
            }else{
                //注册
                TAppUser appUser = new TAppUser();
                appUser.setAppleId(appleId);
                appUser.setCreateTime(new Date());
                appUser.setUpdateTime(new Date());
                appUser.setIsDelete(1);
                user.setUpdateTime(new Date());
                user.setAppVersion(appVersion);
                user.setSysVersion(sysVersion);
                user.setTerminal(terminal);
                tAppUserMapper.insert(appUser);

                //初始化userdata数据
                initAppUserData(appUser.getId());
                user=appUser;
            }
            user=createAppUserLoginToken(user);
            return JsonReturn.success().put("user",user)
                    .put("phoneFlag",user.getPhone()!=null && !user.getPhone().isEmpty()?Boolean.TRUE:Boolean.FALSE)
                    .put("passwordFlag",user.getPassword()!=null && !user.getPassword().isEmpty()?Boolean.TRUE:Boolean.FALSE)
                    .put("registrationAgreementFlag",user.getRegistrationAgreementFlag()!=null && user.getRegistrationAgreementFlag()==1?Boolean.TRUE:Boolean.FALSE)
                    .toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();
    }

    @Override
    public String updateAppUserPassword(LoginParam param) {
        String username = param.getUsername();
        String password = param.getPassword();
        String code = param.getCode();
        if(username==null || username.isEmpty() || password==null || password.isEmpty() || code==null || code.isEmpty()){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("username", username).last("limit 1"));
        if(user!=null && user.getId()!=null){
            String pwdParam  = ToolUtils.makePassword(password);
            user.setPassword(pwdParam);
            tAppUserMapper.updateById(user);
            return JsonReturn.success().toJsonStr();
        }else {
            return JsonReturn.fail("账号不存在",203).toJsonStr();
        }
    }

    /**
     * 修改成新的手机号
     * @param param
     * @return
     */
    @Override
    public String updateAppUserPhone(LoginParam param) {
        Long userId = param.getUserId();
        String phone = param.getPhone();
        String code = param.getCode();
        String codeKey = param.getCodeKey();
        //账号密码登录
        if(phone==null || phone.isEmpty() || code==null || code.isEmpty() || codeKey==null || codeKey.isEmpty()|| userId==null){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        TAppUser user = tAppUserMapper.selectById(userId);
        if(user!=null && user.getId()!=null){
            Object codeKeyData = RedisUtils.get(codeKey);
            if(codeKeyData==null){
                return JsonReturn.fail("验证码已失效",205).toJsonStr();
            }
            if(code.equals(codeKeyData)){
                user.setPhone(phone);
                tAppUserMapper.updateById(user);
                return JsonReturn.success().toJsonStr();
            }
            return JsonReturn.fail("验证码错误",206).toJsonStr();
        }else {
            return JsonReturn.fail("手机号不存在",203).toJsonStr();
        }
    }

    @Override
    public String appUserRegister(LoginParam param) {
        String username = param.getUsername();
        String password = param.getPassword();
        String code = param.getCode();
        String phone = param.getPhone();
        String codeKey = param.getCodeKey();
        Integer loginType = param.getLoginType();
        //账号密码注册
        if(loginType!=null && loginType==1){
            //账号密码注册
            if(username==null || username.isEmpty() || password==null || password.isEmpty() || code==null || code.isEmpty() || codeKey==null || codeKey.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("username", username).last("limit 1"));
            if(user!=null && user.getId()!=null){
                return JsonReturn.fail("账号已经存在",203).toJsonStr();
            }
            Object codeKeyData = RedisUtils.get(codeKey);
            if(codeKeyData==null){
                return JsonReturn.fail("验证码已失效",205).toJsonStr();
            }
            if(code.equals(codeKeyData)){
                String pwdParam  = ToolUtils.makePassword(password);
                TAppUser appUser = new TAppUser();
                appUser.setUsername(username);
                appUser.setPassword(pwdParam);
                appUser.setIsDelete(1);
                tAppUserMapper.insert(appUser);

                createAppUserLoginToken(appUser);
                //初始化userdata数据
                initAppUserData(appUser.getId());
                return JsonReturn.success().toJsonStr();
            }
            return JsonReturn.fail("验证码错误",206).toJsonStr();
        }
        //手机号验证码注册
        else  if(loginType!=null && loginType==2){
            if(phone==null || phone.isEmpty() || code==null || code.isEmpty() || codeKey==null || codeKey.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).last("limit 1"));
            if(user!=null && user.getId()!=null){
                return JsonReturn.fail("手机号已经存在",203).toJsonStr();
            }
            Object codeKeyData = RedisUtils.get(codeKey);
            if(codeKeyData==null){
                return JsonReturn.fail("验证码已失效",205).toJsonStr();
            }
            if(code.equals(codeKeyData)){
                TAppUser appUser = new TAppUser();
                appUser.setUsername(phone);
                appUser.setPhone(phone);
                appUser.setIsDelete(1);
                tAppUserMapper.insert(appUser);

                createAppUserLoginToken(appUser);

                //初始化userdata数据
                initAppUserData(appUser.getId());
                return JsonReturn.success().toJsonStr();
            }
            return JsonReturn.fail("验证码错误",206).toJsonStr();
        }
        //本机号码一键登录注册
        else  if(loginType!=null && loginType==3){
            if(phone==null || phone.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).last("limit 1"));
            String token = ToolUtils.makeToken();
            if(user!=null && user.getId()!=null){

            }else{
                TAppUser appUser = new TAppUser();
                appUser.setUsername(phone);
                appUser.setPhone(phone);
                appUser.setIsDelete(1);
                tAppUserMapper.insert(appUser);

                //初始化userdata数据
                initAppUserData(appUser.getId());
                user=appUser;
            }

            createAppUserLoginToken(user);
            return JsonReturn.success().put("user",user).toJsonStr();
        }
        //微信一键登录注册
        else  if(loginType!=null && loginType==4){
//            if(phone==null || phone.isEmpty()){
//                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
//            }
//            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).last("limit 1"));
//            String token = ToolUtils.makeToken();
//            if(user!=null && user.getId()!=null){
//                user.setToken(token);
//                tAppUserMapper.updateById(user);
//            }else{
//                TAppUser appUser = new TAppUser();
//                appUser.setPhone(phone);
//                appUser.setToken(token);
//                tAppUserMapper.insert(appUser);
//            }
//            Long userId = user.getId();
//            return JsonReturn.success().put("user",user).toJsonStr();
        }
        //ios一键登录注册
        else  if(loginType!=null && loginType==5){
//            if(phone==null || phone.isEmpty()){
//                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
//            }
//            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).last("limit 1"));
//            String token = ToolUtils.makeToken();
//            if(user!=null && user.getId()!=null){
//                user.setToken(token);
//                tAppUserMapper.updateById(user);
//            }else{
//                TAppUser appUser = new TAppUser();
//                appUser.setPhone(phone);
//                appUser.setToken(token);
//                tAppUserMapper.insert(appUser);
//            }
//            Long userId = user.getId();
//            return JsonReturn.success().put("user",user).toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();
    }

    /**
     * 忘记密码第一步
     * @param param
     * @return
     */
    @Override
    public String forgotPasswordStepOne(LoginParam param) {
        String phone = param.getPhone();
        String code = param.getCode();
        if(phone==null || phone.isEmpty() || code==null || code.isEmpty()){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        if(!ToolUtils.isValidPhoneNumber(phone)){
            return JsonReturn.fail("手机号格式不正确",301).toJsonStr();
        }
        TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).eq("is_delete",1).last("limit 1"));
        if(user!=null && user.getId()!=null){
            if(!RedisUtils.exists(phone)){
                return JsonReturn.fail("验证码已过期",210).toJsonStr();
            }
            Object codeKeyData =  RedisUtils.get(phone);
            if(codeKeyData==null){
                return JsonReturn.fail("验证码已失效",210).toJsonStr();
            }
            if(code.equals(codeKeyData)){
                RedisUtils.del(phone);
                return JsonReturn.success().put("user",user).toJsonStr();
            }
            return JsonReturn.fail("验证码错误",204).toJsonStr();
        }else {
            return JsonReturn.fail("手机号不存在",203).toJsonStr();
        }
    }

    /**
     * 忘记密码第二步
     * @param param
     * @return
     */
    @Override
    public String forgotPasswordStepTwo(LoginParam param) {
        Long userId = param.getUserId();
        String password = param.getPassword();
        String passwordAgain = param.getPasswordAgain();
        if(userId==null || password==null || password.isEmpty() || passwordAgain==null || passwordAgain.isEmpty()){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        if(!password.equals(passwordAgain)){
            return JsonReturn.fail("两次输入密码不一致",202).toJsonStr();
        }
        TAppUser appUser = tAppUserMapper.selectById(userId);
        String pwdParam  = ToolUtils.makePassword(password);
        appUser.setPassword(pwdParam);
        appUser.setUpdateTime(new Date());
        tAppUserMapper.updateById(appUser);
        return JsonReturn.success().toJsonStr();
    }

    /**
     * 第三方登录绑定手机号
     * @param param
     * @return
     */
    @Override
    public String bindPhone(LoginParam param) {
        Integer loginType = param.getLoginType();
        String phone = param.getPhone();
        String code = param.getCode();
        String codeKey = param.getCodeKey();
        String openId = param.getOpenId();
        String appleId = param.getAppleId();
        if(loginType==null || loginType==0 || phone==null || phone.isEmpty() || code==null || code.isEmpty() || codeKey==null || codeKey.isEmpty()){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        if(!ToolUtils.isValidPhoneNumber(phone)){
            return JsonReturn.fail("手机号格式不正确",301).toJsonStr();
        }
        //微信一键登录
        if(loginType==4){
            if(openId==null || openId.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            Object codeKeyData = RedisUtils.get(codeKey);
            if(code.equals(codeKeyData)){
                TAppUser appUser = new TAppUser();
                appUser.setPhone(phone);
                tAppUserMapper.update(appUser, new QueryWrapper<TAppUser>().eq("open_id", openId));
                return JsonReturn.success().toJsonStr();
            }
            return JsonReturn.fail("验证码错误",206).toJsonStr();
        }
        //ios一键登录
        else if(loginType==5){
            if(appleId==null || appleId.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            Object codeKeyData = RedisUtils.get(codeKey);
            if(code.equals(codeKeyData)){
                TAppUser appUser = new TAppUser();
                appUser.setPhone(phone);
                tAppUserMapper.update(appUser, new QueryWrapper<TAppUser>().eq("apple_id", appleId));
                return JsonReturn.success().toJsonStr();
            }
            return JsonReturn.fail("验证码错误",206).toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();
    }

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public TAppUser selectById(Integer userId) {

        TAppUser appUser = tAppUserMapper.selectById(userId);
        return appUser;
    }

    /**
     * 修改用户信息
     * @param appUser
     * @return
     */
    @Override
    public String updateById(TAppUser appUser) {
        Long userId = appUser.getId();
        if(userId==null || userId==0){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        int i = tAppUserMapper.updateById(appUser);
        if(i==1){
            return JsonReturn.success().toJsonStr();
        }
        return JsonReturn.fail("服务器错误，修改失败",202).toJsonStr();
    }

    /**
     * 查询个人中心的用户信息（实时）
     * @param userId
     * @return
     */
    @Override
    public String selectUserForPersonalCenter(Integer userId) {
        if(userId==null || userId==0){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        TAppUser appUser = tAppUserMapper.selectById(userId);
        TAppUserData appUserData = appUserDataMapper.selectOne(new QueryWrapper<TAppUserData>().eq("user_id",userId));
        if(appUser!=null){
            AppUserDTO appUserDTO = Optional.ofNullable(AppUserDTO.toAppUserDTO(appUser)).orElse(new AppUserDTO());
            //企业数据
            AppEnterpriseDTO appEnterpriseDTO = new AppEnterpriseDTO();
            if(appUserData!=null && appUserData.getId()!=null){
                appUserDTO.setUserDataId(appUserData.getId());
                Integer enterpriseId = appUserData.getEnterpriseId();
                if(enterpriseId!=null){
                    TAppEnterprise appEnterprise = appEnterpriseMapper.selectById(enterpriseId);
                    appEnterpriseDTO = AppEnterpriseDTO.toAppEnterpriseDTO(appEnterprise);
                }
            }
            appUserDTO.setEnterpriseDTO(appEnterpriseDTO);
            return JsonReturn.success().put("appUserDTO",appUserDTO).toJsonStr();
        }
        return JsonReturn.fail("用户不存在",201).toJsonStr();
    }

    /**
     * 增加用户访客数量
     * @param userId
     * @return
     */
    @Override
    public String updateAppUserVisitorNumById(Integer userId) {
        if(userId==null || userId==0){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        TAppUser appUser = tAppUserMapper.selectById(userId);
        if(appUser!=null){
            Integer num = Optional.ofNullable(appUser.getVisitorNum()).orElse(0);
            appUser.setVisitorNum(num+1);
            tAppUserMapper.updateById(appUser);
            return JsonReturn.success().toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();
    }

    /**
     * 验证用户是否绑定企业
     * @param userId
     * @return
     */
    @Override
    public String checkUserEnterpriseFlag(Integer userId) {
        if(userId==null || userId==0){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        List<TAppEnterprise> appEnterpriseList = Optional.ofNullable(appEnterpriseMapper.selectList(new QueryWrapper<TAppEnterprise>().eq("user_id",userId))).orElse(new ArrayList<>());
        if(appEnterpriseList.size()>0){
            return JsonReturn.success().put("flag",Boolean.TRUE).toJsonStr();
        }
        return JsonReturn.success().put("flag",Boolean.FALSE).toJsonStr();
    }

    /**
     * 第三方登录设置密码
     * @param param
     * @return
     */
    @Override
    public String bindPassword(LoginParam param) {
        Integer loginType = param.getLoginType();
        String password = param.getPassword();
        String passwordAgain = param.getPasswordAgain();
        String openId = param.getOpenId();
        String appleId = param.getAppleId();
        String phone = param.getPhone();
        if(loginType==null || loginType==0 || password==null || password.isEmpty() || passwordAgain==null || passwordAgain.isEmpty()){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        if(!password.equals(passwordAgain)){
            return JsonReturn.fail("两次密码不一致",202).toJsonStr();
        }
        //手机号设置密码
        if(loginType==2 || loginType ==3){
            if(phone==null || phone.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            if(!ToolUtils.isValidPhoneNumber(phone)){
                return JsonReturn.fail("手机号格式不正确",301).toJsonStr();
            }
            TAppUser appUser = new TAppUser();
            String pwdParam  = ToolUtils.makePassword(password);
            appUser.setPassword(pwdParam);
            tAppUserMapper.update(appUser, new QueryWrapper<TAppUser>().eq("phone", phone));
            return JsonReturn.success().toJsonStr();
        }
        //微信一键登录
        if(loginType==4){
            if(openId==null || openId.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            TAppUser appUser = new TAppUser();
            String pwdParam  = ToolUtils.makePassword(password);
            appUser.setPassword(pwdParam);
            tAppUserMapper.update(appUser, new QueryWrapper<TAppUser>().eq("open_id", openId));
            return JsonReturn.success().toJsonStr();
        }
        //ios一键登录
        else if(loginType==5){
            if(appleId==null || appleId.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            TAppUser appUser = new TAppUser();
            String pwdParam  = ToolUtils.makePassword(password);
            appUser.setPassword(pwdParam);
            tAppUserMapper.update(appUser, new QueryWrapper<TAppUser>().eq("apple_id", appleId));
            return JsonReturn.success().toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();

    }

    /**
     * 发送短信验证码
     * @param param
     * @return
     */
    @Override
    public String sendSms(LoginParam param) {
        String phone = param.getPhone();
        Integer smsType = param.getSmsType();
        if(phone==null || phone.isEmpty() || smsType==null || smsType==0){
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        if(!ToolUtils.isValidPhoneNumber(phone)){
            return JsonReturn.fail("手机号格式不正确",301).toJsonStr();
        }
        String smsCodeKey = createSmsCodeKey();
        String smsCodeValue = createSmsCodeValue();
        Map<String, String> map = new HashMap<>();
        map.put("code", smsCodeValue);
        String smsTemplate = SmsUtil.TEMPLATE.SMS_test;
        //验证码登录
        if(smsType==2){
            smsTemplate=SmsUtil.TEMPLATE.SMS_login;
        }
        //绑定/修改手机号码
        else if (smsType==3) {
            smsTemplate=SmsUtil.TEMPLATE.SMS_change_phone;
        }
        //忘记/重置密码
        else if (smsType==4) {
            smsTemplate=SmsUtil.TEMPLATE.SMS_reset_password;
        }
        //企业认证/绑定企业
        else if (smsType==5) {
            smsTemplate=SmsUtil.TEMPLATE.SMS_enterprise_certification;
        }
        //注销账户
        else if (smsType==6) {
            smsTemplate=SmsUtil.TEMPLATE.SMS_unsubscribe;
        }
        Pair<Integer, String> pair = SmsUtil.sendAliyunSMS(phone, smsTemplate, map);
        if(pair.getKey()!=null && pair.getKey()==2){
            //放进redis中
            RedisUtils.set(phone, smsCodeValue, 60*1000);
            return JsonReturn.success().put("smsCodeKey",smsCodeKey).toJsonStr();
        }
        return JsonReturn.fail().toJsonStr();
    }

    @Override
    public TAppUser selectUserByToken(String token) {
        if(token!=null && !token.isEmpty()){
            TAppUser user = tAppUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("token", token));
            if(user!=null){
                return user;
            }
        }
        return new TAppUser();
    }

    @Override
    public String loginOut(LoginParam param) {
        Long userId = param.getUserId();
        if(userId!=null && userId>0){
            TAppUser user = tAppUserMapper.selectById(userId);
            user.setToken("");
            user.setTokenEndTime(new Date());
            tAppUserMapper.updateById(user);
            return JsonReturn.success().toJsonStr();
        }
        return JsonReturn.fail("必传参数不能为空！",40001).toJsonStr();
    }

    /**
     *  注销账户
     * @param param
     * @return
     */
    @Override
    public String cancelAccount(LoginParam param) {
        Long userId = param.getUserId();
        Integer loginType = param.getLoginType();
        String phone = param.getPhone();
        String password = param.getPassword();
        String code = param.getCode();
        if(userId==null || userId<=0 || loginType==null || loginType==0){
            return JsonReturn.fail("必传参数不能为空！",40001).toJsonStr();
        }
        TAppUser user = tAppUserMapper.selectById(userId);
        if(user!=null && user.getId()!=null){
            return JsonReturn.fail("账号不存在",203).toJsonStr();
        }
        //todo 1.会员是否到期; 2.余额（佣金和领企币）是否为0; 3：报告是否在生成中状态;


        //账号密码验证
        if(loginType==1){
            if(phone==null || phone.isEmpty() || password==null || password.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            if(!ToolUtils.isValidPhoneNumber(phone)){
                return JsonReturn.fail("手机号格式不正确",301).toJsonStr();
            }
            String pwd = user.getPassword();
            if(pwd==null || pwd.isEmpty()){
                return JsonReturn.fail("账号未设置密码",208).toJsonStr();
            }
            String pwdParam  = ToolUtils.makePassword(password);
            if(!pwd.equals(pwdParam)){
                return JsonReturn.fail("密码输入错误",202).toJsonStr();
            }
        }
        //手机号验证码验证
        else if(loginType==2){
            if(phone==null || phone.isEmpty() || code==null || code.isEmpty()){
                return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
            }
            if(!ToolUtils.isValidPhoneNumber(phone)){
                return JsonReturn.fail("手机号格式不正确",301).toJsonStr();
            }
            if(!RedisUtils.exists(phone)){
                return JsonReturn.fail("验证码已过期",210).toJsonStr();
            }
            Object codedata = RedisUtils.get(phone);
            if(!code.equals(codedata)){
                return JsonReturn.fail("验证码错误",206).toJsonStr();
            }
        }
        user.setIsDelete(2);
        tAppUserMapper.updateById(user);
        return JsonReturn.success().toJsonStr();
    }


    /**
     * 刷新用户token
     * @param user
     */
    public TAppUser createAppUserLoginToken(TAppUser user) {
        Integer terminal = Optional.ofNullable(user.getTerminal()).orElse(0);
        Integer timeout=  60*60*1000;
        String token = ToolUtils.makeToken();
        Date tokenEndTime = user.getTokenEndTime();
        if(user.getToken()!=null && !user.getToken().isEmpty() && tokenEndTime!=null && tokenEndTime.getTime()>new Date().getTime()){
            token = user.getToken();
        }

        //刷新用户token
        user.setToken(token);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MILLISECOND,timeout);
        user.setTokenEndTime(calendar.getTime());
        tAppUserMapper.updateById(user);

        TokenLoginCache.setFun(token, user.getId(), String.valueOf(terminal),timeout);
        LikeFrontThreadLocal.put("token", token);
        LikeFrontThreadLocal.put("terminal", terminal);
        LikeFrontThreadLocal.put("userId", user.getId());
//        LikeFrontThreadLocal.put("token", token);
//        LikeFrontThreadLocal.put("terminal", 6);
//        Integer i = TokenLoginCache.get();
//        SessionHelper.saveMobileUser(request,response,user);

        Integer userId = TokenLoginCache.get();
        return user;
    }


    /**
     * 创建发送短信的key值
     * @return
     */
    public String createSmsCodeKey() {
        String s = ToolUtils.randomString(6);
//        RedisUtils.set(KEY, 1111);
//        Object o = RedisUtils.get(KEY);
        return new Date().getTime() + s;
    }

    /**
     * 创建发送短信的value值
     * @return
     */
    public String createSmsCodeValue(){
        String s = ToolUtils.randomInt(6);
        return s;
    }

    public void initAppUserData(Long userId) {
        TAppUserData appUserData = new TAppUserData();
        appUserData.setUserId(Math.toIntExact(userId));
        appUserData.setCreateTime(new Date());
        appUserData.setUpdateTime(new Date());
        appUserDataMapper.insert(appUserData);
    }

}
